package com.lgc.javathread.threadWaitTest.conditionTest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConTest {
    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        ConTest test = new ConTest();
        Producer producer = test.new Producer();
        Consumer consumer1 = test.new Consumer();
        Consumer consumer2 = test.new Consumer();

        consumer1.start();
        consumer2.start();

        Thread.sleep(2000);

        producer.start();

        Thread.sleep(2000);
        consumer2.interrupt();
    }

    class Consumer extends Thread {
        @Override
        public void run() {
            consume();
        }

        private void consume() {
            try {
                lock.lock();
                System.out.println("我在等一个新信号" + Thread.currentThread().getName());
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("拿到一个信号" + Thread.currentThread().getName());
                lock.unlock();
            }
        }
    }

    class Producer extends Thread {
        @Override
        public void run() {
            produce();
        }

        private void produce() {
            try {
                lock.lock();
                System.out.println("我拿到锁" + Thread.currentThread().getName());

                //condition的signal是将等待队列中的first节点放入同步队列，并通过调用unpark(AQS里的LockSupport的方法)方法来唤醒线程。
                // signalAll就是signal的while循环，将所有等待队列中的node放入同步队列，并逐一唤醒。

                condition.signal();//signal就是唤醒该队列的第一个线程节点
//                condition.signalAll(); // signalAll唤醒同一个条件变量的所有线程去争锁
                System.out.println("我发出了一个信号：" + Thread.currentThread().getName());
            } finally {
                lock.unlock();
            }
        }
    }
}
